<template>
  <div>

    <el-row>
      <el-col :span="4">
        <el-table
          ref="codeTable"
          empty-text="请先选择字段"
          v-loading="loadValue"
          :data="valueList.slice((current-1)*size, current*size)"
          row-key="codeValue"
          highlight-current-row
          border
          @current-change="handleCurrentChange">
          <el-table-column :filters="filters" :filter-multiple="false" :filter-method="filterMethod" draggable prop="codeValue" align="center" label="编码(点击筛选)"
                           :show-overflow-tooltip="true">
            <template slot-scope="scope" v-if="scope.row.dimensionDetailId==undefined">
              <draggable :group="{name: 'codeValue' , pull: 'clone', put: false}" @end="handleEnd">
                <el-tooltip v-if="scope.row.notAuto===0" :hide-after=1000 class="item" effect="light" content="不可批量执行"
                            placement="top-end">
                  <div class="cell" style="color: red" :key="scope.row.codeValue">{{ scope.row.codeValue }}</div>
                </el-tooltip>
                <el-tooltip v-else-if="scope.row.notAuto===1" :hide-after=1000 class="item" effect="light"
                            content="可批量执行" placement="top-end">
                  <div class="cell" style="color: #36a3f7" :key="scope.row.codeValue">{{ scope.row.codeValue }}</div>
                </el-tooltip>
                <el-tooltip v-else-if="scope.row.notAuto===2" class="item" effect="light" :hide-after=1000
                            content="已存在" placement="top-end">
                  <div class="cell" :key="scope.row.codeValue">{{ scope.row.codeValue }}</div>
                </el-tooltip>
                <div class="cell" v-else :key="scope.row.codeValue">{{ scope.row.codeValue }}</div>
              </draggable>
            </template>
          </el-table-column>
        </el-table>

        <el-pagination
          small
          layout="prev, pager, next"
          v-show="total>0"
          :total="total"
          :page-size="size"
          @current-change="currentPageChange">
        </el-pagination>
      </el-col>
      <el-col :span="19" :offset="1">

        <el-form :model="queryParams" ref="queryForm" :inline="true">
          <el-form-item label="维度名称" prop="dimensionNames">
            <el-input v-model="queryParams.dimensionName" placeholder="请输入维度名称" style="width:150px">></el-input>
          </el-form-item>
          <el-form-item label="维度编码" prop="dimensionCode">
            <el-input v-model="queryParams.dimensionCode" style="width:100px"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
            <el-button icon="el-icon-thumb" size="small" @click="autoMarkCode">编码批量对应</el-button>
            <el-button type="primary" icon="el-icon-plus" size="small" @click="handleAddBtn"
                       v-if="codeValue" v-hasPermi="['quota:dimension:add']">新增
            </el-button>
          </el-form-item>

        </el-form>
        <el-table
          height="515"
          class="detailTable"
          ref="detailTable"
          v-loading="loadDetail"
          :data="detailList"
          row-key="dimensionId"
          border
          lazy
          :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
        >
          <el-table-column label="维度名称" prop="dimensionName" :show-overflow-tooltip="true"/>
          <el-table-column label="维度编码" align="center" prop="dimensionCode" width="100px"
                           :show-overflow-tooltip="true"/>
          <el-table-column label="对应编码" align="center" prop="codeValue" width="100px">
            <template slot-scope="scope">
              {{ scope.row.codeValue }}
              <draggable v-if="typeof(scope.row.codeValue)!='string'" group="codeValue" :id="scope.row.dimensionId"
                         draggable="false" @add="addCode(scope.row)">
              </draggable>
            </template>
          </el-table-column>
          <el-table-column label="年份" align="center" prop="activeYear" width="70px"/>
          <el-table-column fixed="right" label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-tooltip content="新增为子维度" placement="bottom">
                <el-button
                  v-if="codeValue"
                  size="mini"
                  type="text"
                  icon="el-icon-plus"
                  @click="handleAdd(scope.row)"
                >新增
                </el-button>
              </el-tooltip>
              <el-tooltip content="删除当前对应关系" placement="bottom">
                <el-button
                  v-if="scope.row.codeValue"
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.row)"
                >删除
                </el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <el-dialog title="添加维度" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-form-item label="对应维度">
            <el-input v-model="form.codeValue" readonly></el-input>
          </el-form-item>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="维度名称">
              <el-input v-model="form.dimensionName" placeholder="请输入维度名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="维度编码">
              <el-input v-model="form.dimensionCode"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="使用年份">
              <el-date-picker
                v-model="form.activeYear"
                type="year"
                value-format="yyyy"
                placeholder="选择年份">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in statusOptions"
                  :key="dict.dictValue"
                  :label="dict.dictValue"
                >{{ dict.dictLabel }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="维度类型">
              <el-select v-model="form.dimensionType" placeholder="请选择维度类型">
                <el-option
                  v-for="dict in dimensionTypeOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="维度属性">
              <el-select v-model="form.dimensionAttr" placeholder="请选择维度属性">
                <el-option
                  v-for="dict in dimensionAttrOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-form-item label="维度说明">
            <el-input type="textarea" v-model="form.comments"></el-input>
          </el-form-item>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="可批量对应编码维度项"
      :visible.sync="autoMarkOpen"
      width="30%">
      <span>
        <el-table
          :data="autoMarkCodes.slice((autoMarkCurrent-1)*autoMarkSize, autoMarkCurrent*autoMarkSize)"
          row-key="dimensionId"
          border>
          <el-table-column label="维度名称" prop="dimensionName" :show-overflow-tooltip="true"/>
          <el-table-column label="维度编码" align="center" prop="dimensionCode" width="100px"
                           :show-overflow-tooltip="true"/>
          <el-table-column label="对应编码" align="center" prop="codeValue" width="100px">
          </el-table-column>
          <el-table-column label="年份" align="center" prop="activeYear" width="70px"/>
        </el-table>
        <el-pagination
          small
          layout="prev, pager, next"
          v-show="autoMarkCodes.length>0"
          :total="autoMarkCodes.length"
          :page-size="autoMarkSize"
          @current-change="autoMarkPage">
        </el-pagination>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="autoMarkOpen = false">取 消</el-button>
        <el-button type="primary" @click="submitAutoMark">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import draggable from 'vuedraggable'
import {
  add,
  addDimensionDetail,
  batchAdd,
  columnValue,
  delDimensionDetail,
  selectColumnDimenstionDetail
} from '@/api/metadata/detail'
import Cookies from 'js-cookie'

export default {
  name: 'DetailValue',
  components: { draggable },
  props: {
    datasourceId: {
      type: Number
    },
    colnameAliasId: {
      type: Number
    },
    columnAlias: {
      type: String
    }
  },
  data() {
    return {
      loading: false,
      loadValue: false,
      loadDetail: false,
      //以下五个为自动对应编码使用数据
      autoMarkOpen: false,
      autoMarkCodes: [],
      autoMarkDetails: [],
      autoMarkSize: 10,
      autoMarkCurrent: 1,
      //table筛选类型
      filters: [{
        text: '不可批量操作',
        value: 0
      }, {
        text: '可批量操作',
        value: 1
      }, {
        text: '已存在',
        value: 2
      }],
      total: 0,
      size: 12,
      current: 1,
      valueList: [],  // 选定列值集合
      upperId: 0,
      open: false,
      codeValue: undefined,
      detailList: [],
      droppedItem: '',
      row: {},
      queryParams: {
        datasourceId: undefined,
        colnameAliasId: undefined,
        codeValue: undefined,
        dimensionCode: undefined
      },
      form: {
        codeValue: undefined
      },
      rules: {
        dimensionName: [
          { required: true, message: '维度名称不能为空', trigger: 'blur' },
          { max: 50, message: '最大长度为50个字符', trigger: 'blur' }
        ],
        dimensionCode: [
          { required: true, message: '维度编码不能为空', trigger: 'blur' },
          { max: 50, message: '最大长度为25个字符', trigger: 'blur' }
        ],
        comments: [
          { max: 500, message: '最大长度为500个字符', trigger: 'blur' }
        ]
      },
      // 维度类型：1,公用;2,私有
      dimensionTypeOptions: [{ dictValue: '1', dictLabel: '公用' }, { dictValue: '2', dictLabel: '私有' }],
      // 维度属性：1,动态;2.静态
      dimensionAttrOptions: [{ dictValue: '1', dictLabel: '动态' }, { dictValue: '2', dictLabel: '静态' }],
      statusOptions: [{ dictValue: '1', dictLabel: '启用' }, { dictValue: '2', dictLabel: '禁用' }]
    }
  },
  watch: {
    colnameAliasId: {
      immediate: true, //立即触发回调，为解决dialog中显示控件不触发watch问题
      handler(newVal, oldVal) {
        if (!newVal) {
          return
        }
        this.queryParams.colnameAliasId = newVal
        this.queryParams.codeValue = undefined
        this.getValueList()
        this.getDetailList()
      }
    },
    datasourceId: {
      immediate: true,
      handler(newVal, oldVal) {
        this.queryParams.datasourceId = newVal
      }
    }
  },
  methods: {
    // 复位表单
    reset() {
      this.form = {
        datasourceId: this.datasourceId,
        colnameId: this.colnameAliasId,
        codeValue: this.codeValue,
        dimensionName: undefined,
        dimensionCode: undefined,
        dimensionType: '1',
        dimensionAttr: '1',
        status: '1',
        updateDate: undefined,
        comment: undefined,
        activeYear: new Date().getFullYear() + '',
        updateBy: Cookies.get('username')
      }
      this.resetForm('form')
    },
    // 获取字段值列表
    getValueList() {
      this.loading = true
      this.loadValue = true
      let tempValues = []
      columnValue(this.queryParams).then(response => {
        for (let code of response.data) {
          tempValues.push({ codeValue: code })
        }
        this.total = response.data.length
        this.valueList = tempValues
        this.loadValue = false
        if (this.loadDetail) {
          this.loading = false
        }
      })
    },
    // 获取维度明细列表
    getDetailList(row, treeNode, resolve) {
      this.loading = true
      this.loadDetail = true
      this.queryParams.upperId = this.upperId
      this.queryParams.colnameId = this.queryParams.colnameAliasId
      // selectColumnDimenstionDetail({upperId: this.upperId, colnameId: this.queryParams.colnameAliasId}).then(response => {
      selectColumnDimenstionDetail(this.queryParams).then(response => {
        this.autoMarkDetails = response.data
        this.detailList = this.handleTree(response.data, 'dimensionId', 'upperId')
        console.log('this.detailList')
        console.log(this.detailList)
        this.loadDetail = false
        if (this.loadValue) {
          this.loading = false
        }
      })
    },
    //提交要批量对应的数据
    submitAutoMark() {
      this.$confirm('是否需要再次检查?', '警告', {
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        type: 'warning'
      }).then(() => {
        batchAdd(this.autoMarkCodes).then((res) => {
          if (res.code === 0) {
            this.$message({
              message: '数据已提交',
              type: 'success'
            })
            this.autoMarkCodes = []
            this.autoMarkOpen = false
            this.getDetailList()
          }
        })
      }).catch(() => {
      })
      this.autoMarkOpen = false
    },
    //相同编码自动对应
    autoMarkCode() {
      if (this.autoMarkDetails.length <= 0 || this.valueList.length <= 0) {
        this.$message({
          message: '请等待数据加载完成',
          type: 'warning'
        })
        return
      }
      let autoCodes = []
      this.valueList.forEach(value => {
        let index = this.autoMarkDetails.findIndex(detail => {
          return detail.dimensionCode == value.codeValue
        })
        if (index != -1) {
          let detail = this.autoMarkDetails[index]
          if (!detail.codeValue) {
            let obj = JSON.parse(JSON.stringify(detail))
            obj.codeValue = value.codeValue
            obj.colnameId = this.colnameAliasId
            autoCodes.push(obj)
            this.$set(value,'notAuto',1)
          } else {
            this.$set(value,'notAuto',2)
          }
        } else {
          this.$set(value,'notAuto',0)
        }
      })
      if (autoCodes.length <= 0) {
        this.$message({
          message: '暂无可批处理项',
          type: 'warning'
        })
        return
      }
      this.autoMarkCodes = autoCodes
      this.autoMarkOpen = true
    },
    autoMarkPage(currentPage) {
      this.autoMarkCurrent = currentPage
    },
    // 选择字段值
    handleCurrentChange(val) {
      // this.form.codeValue = val.codeValue
      this.codeValue = val.codeValue
    },
    // 当前页码 （用于字段值）
    currentPageChange(currentPage) {
      this.current = currentPage
    },
    // 新增按钮操作
    handleAddBtn() {
      this.handleAdd()
    },
    // 新增维度
    handleAdd(row) {
      this.reset()
      if (row) {
        this.form.upperId = row.dimensionId
      } else {
        this.form.upperId = 0
      }
      this.open = true
      this.title = '添加维度详情'
    },
    // 复位查询
    resetQuery() {
      this.resetForm('queryForm')
      this.getDetailList()
    },
    // 取消dialog
    cancel() {
      this.open = false
      this.reset()
    },
    // 提交
    submitForm(row) {
      addDimensionDetail(this.form).then(response => {
        if (response.code === 0) {
          this.open = false
          this.msgSuccess('新增完成')
          if (row) {
            row.codeValue = this.codeValue
            row.dimensionDetailId = response.data
          } else {
            this.getDetailList()
          }
        }

      })
    },
    handleQuery() {
      this.getDetailList()
    },
    handleDelete(row) {
      this.$confirm('是否确认删除?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return delDimensionDetail(row.dimensionDetailId)
      }).then(() => {
        row.dimensionDetailId = undefined
        row.codeValue = undefined

        // this.refreshRow(row.upperId)
      }).catch(function() {
      })
    },
    handleEnd(e) {
      if (this.row.codeValue) {
        return
      }
      this.codeValue = e.from.innerText
      this.reset()
      add({
        dimensionId: this.row.dimensionId,
        codeValue: this.codeValue,
        colnameId: this.colnameAliasId
      }).then(response => {
        if (response.code === 0) {
          this.refreshRow(this.row.dimensionId)
        }
      })
    },
    addCode(row) {
      this.row = row
    },
    //刷新table treenode
    refreshRow(id) {
      selectColumnDimenstionDetail({ dimensionId: id, colnameId: this.colnameAliasId }).then(response => {
        if (response.code === 0) {
          this.row.codeValue = response.data[0].codeValue
          this.row.dimensionDetailId = response.data[0].dimensionDetailId
        }
      })
    },
    //table筛选
    filterMethod(value, row){
      return row.notAuto === value;
    }
  }
}
</script>

<style scoped>
/deep/ .el-table__body tr.current-row > td {
  background-color: #6eadff !important;
  color: #fff;
}
</style>
